//
// Created by chizuru on 2025/9/26.
//
#include <windows.h>
#include "xcliball.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include "test-live-demo.h"
#include <numeric>
#include <thread>
#include "TinyXmlRegisterCLBMap.h"
#include "PxdSerialAdapter.h"
#include "DeviceComm.h"
#include "RegisterReadCommand.h"
#include "BOBCATCameraService.h"
#include "ProtocolCodecFactory.h"
#include "ConnectivityMonitor.h"
#include "aop.hpp"
#include "libserialport.h"
using namespace std;
int openXClib(){
    // 初始化 XCLIB
    int ret = pxd_PIXCIopen(/*"-IM 327680000 -MB 65536 -CQ 512 -BS 1 -DM 15 -PO 5000 -XU 1 -XM 1 -MU 106 -QU 1 -QS 1 -TI 1 -SB 1024"*/"", "", "es.fmt"); // 根据设备初始化参数配置
    if (ret < 0) {
        std::cerr << pxd_mesgErrorCode(ret) << std::endl;
        return -1;
    }
    return 0;
}

int closeXClib(){
    int ret = pxd_PIXCIclose();
    if (ret < 0) {
        std::cerr << "Failed to close XCLIB, error code: " << ret << std::endl;
        return -1;
    }
    return 0;
}

void test1(){
    std::shared_ptr<TinyXmlRegisterCLBMap> regMap;
    try {
        regMap = std::make_shared<TinyXmlRegisterCLBMap>("regs_generated.xml");
    } catch (...) {

    }

    PxdSerialAdapter serialAdapter(1);
    DeviceComm comm(serialAdapter);
    comm.configureSerial(115200, 8, 0, 1, 0);
    CameraDevice camera(comm, ProtocolCodecFactory::instance().create("camera_link_default"));

    BOBCATCameraService svs(camera, regMap);

    assert(svs.checkIfCameraConnected().success);
    ConnectivityMonitor monitor(
            [&svs](){ return svs.checkIfCameraConnected().success;},
            [](bool connected){ std::cout << "Camera " << (connected ? "connected" : "disconnected") << std::endl; },
            chrono::milliseconds (2000)
    );
}

void test2() {
    openXClib();
    std::shared_ptr<TinyXmlRegisterCLBMap> regMap;
    try {
        regMap = std::make_shared<TinyXmlRegisterCLBMap>("regs_generated.xml");
    } catch (...) {

    }

    PxdSerialAdapter serialAdapter(1);
    DeviceComm comm(serialAdapter);
    comm.configureSerial(115200, 8, 0, 1, 0);
    CameraDevice camera(comm, ProtocolCodecFactory::instance().create("camera_link_default"));

    BOBCATCameraService svs(camera, regMap);
    auto t = std::jthread(liveThread2, 1, "live1");
    getchar();

    t.request_stop();
    closeXClib();
}